package com.bruce.tool.netty.socket.netty.chat3;

import com.bruce.tool.common.util.LogUtils;
import com.bruce.tool.common.util.string.JsonUtils;
import com.bruce.tool.common.util.string.MapHandler;
import com.bruce.tool.common.util.string.StringUtils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
@Sharable
public class ChatServerHandler extends ChannelInboundHandlerAdapter {

    private ChannelGroup group;

    public ChatServerHandler(ChannelGroup group) {
        this.group = group;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        // 添加渠道
        this.group.add(ctx.channel());
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        // 删除渠道
        this.group.remove(ctx.channel());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String message = toString(msg);
        if (StringUtils.isEmpty(message)){
            return;
        }
        if( message.contains("ping") ){
            LogUtils.info(log,"心跳检测:{}",message);
            Map body = MapHandler.build().add("pong","服务器回复心跳");
            message = JsonUtils.objToStr(body);
            msg = Unpooled.copiedBuffer(message.getBytes());
            Channel incoming = ctx.channel();
            for (Channel channel : group) {
                if (channel == incoming){
                    channel.writeAndFlush(msg);
                }
            }
            return;
        }
        Channel incoming = ctx.channel();
        for (Channel channel : group) {
            if (channel != incoming){ // 和当前渠道不同的渠道,则发送消息;原因,目前的socketclient只有2个,一个作为通信的服务器方,一个作为通信的客户方
                channel.writeAndFlush(msg);
            }
        }
    }

    public String toString(Object data) {
        if( !(data instanceof ByteBuf) ){
            return "";
        }
        ByteBuf buf = (ByteBuf)data;
        String str;
        if(buf.hasArray()) { // 处理堆缓冲区
            str = new String(buf.array(), buf.arrayOffset() + buf.readerIndex(), buf.readableBytes());
        } else { // 处理直接缓冲区以及复合缓冲区
            byte[] bytes = new byte[buf.readableBytes()];
            buf.getBytes(buf.readerIndex(), bytes);
            str = new String(bytes, 0, buf.readableBytes());
        }
        return str;
    }

}